package com.think.oauth.user.security.token;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import com.think.common.model.CustomUser;
import com.think.common.utils.JSonUtil;
import com.think.common.utils.JWTUtils;
import com.think.common.utils.NetUtils;
import com.think.common.utils.RandomUtils;
import com.think.oauth.user.service.CustomUserDetailsService;

public class ILabTokenCustomTokenGranter extends AbstractCustomTokenGranter {

	private CustomUserDetailsService userDetailsService;
	public ILabTokenCustomTokenGranter(AuthorizationServerTokenServices tokenServices,
			ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, CustomUserDetailsService userDetailsService) {
		super(tokenServices, clientDetailsService, requestFactory, "ilab_token");
		// TODO Auto-generated constructor stub
		this.userDetailsService = userDetailsService;
	}

	@Override
	protected UserDetails getUserDetails(Map<String, String> parameters){
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		// TODO Auto-generated method stub
		String ticket = tokenRequest.getRequestParameters().get("token");
		String appId = tokenRequest.getRequestParameters().get("appid");
		String appSecretKey = tokenRequest.getRequestParameters().get("appsecret");
//		String ticket =  "udhK4eTKk67bmlCRBqgaUnJSKZFtXBDMnFQU5aODPRrMtqXo2SO%2BBWaqAYOsCSV1zKjJc9tJV%2F4TnlG5iQLcKlO5UqMbGk%2BWRL3gudRnIlw%3D";//tokenRequest.getRequestParameters().get("token");
		String source =ticket + appId + appSecretKey;
		String encodeTicket = DigestUtils.md5Hex(source ).toUpperCase();
		String url = String.format("%s/open/api/v2/token?ticket=%s&appid=%s&signature=%s"
				,appId.equals("100400") ?"http://202.205.145.156:8017":"http://www.ilab-x.com",URLEncoder.encode(ticket)
				,appId.toString(),encodeTicket);
		
		try {
			String result = NetUtils.doGet(url);
		 	Map<String, Object> map = JSonUtil.getJsonObj(result) ;
			CustomUser userDetails = (CustomUser)this.userDetailsService.loadUserByIlabUsername(map.get("un").toString(),map.get("dis").toString(),map.get("access_token").toString());
			OAuth2Authentication auth2Authentication = new OAuth2Authentication(tokenRequest.createOAuth2Request(client), new UsernamePasswordAuthenticationToken(userDetails, "N/A",userDetails.getAuthorities()));
			auth2Authentication.setAuthenticated(true);
			auth2Authentication.setDetails(userDetails);
			return auth2Authentication;
		} catch (Exception e) {//	SbYymvfZ8UjEmShxRAB0b1Dtaa0uGjDOOJa/f0Mbuo4=
			// TODO: handle exception
			 throw new InvalidGrantException(e.getLocalizedMessage());

		}
		
	}
	
	

}